<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>MordenJava03 | 静待花开</title><meta name="author" content="brad 随风起舞"><meta name="copyright" content="brad 随风起舞"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="来玩玩java的Streampublic class HighCaloriesNames &#123;  public static void main(String[] args) &#123;    List&lt;String&gt; names &#x3D; menu.stream()        .filter(dish -&gt; &#123;          System.out.prin">
<meta property="og:type" content="article">
<meta property="og:title" content="MordenJava03">
<meta property="og:url" content="https://zhangbo4881820.gitee.io/myblog/posts/11006/index.html">
<meta property="og:site_name" content="静待花开">
<meta property="og:description" content="来玩玩java的Streampublic class HighCaloriesNames &#123;  public static void main(String[] args) &#123;    List&lt;String&gt; names &#x3D; menu.stream()        .filter(dish -&gt; &#123;          System.out.prin">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2019-11-08T11:45:45.000Z">
<meta property="article:modified_time" content="2023-09-07T09:44:01.889Z">
<meta property="article:author" content="brad 随风起舞">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/myblog/img/favicon.png"><link rel="canonical" href="https://zhangbo4881820.gitee.io/myblog/posts/11006/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/myblog/css/index.css"><link rel="stylesheet" href="/myblog/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="/myblog/css/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/myblog/',
  algolia: undefined,
  localSearch: {"path":"/myblog/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'MordenJava03',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2023-09-07 17:44:01'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 7.0.0-rc2"><link rel="alternate" href="/myblog/atom.xml" title="静待花开" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/myblog/" title="静待花开"><span class="site-name">静待花开</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">MordenJava03</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-11-08T11:45:45.000Z" title="发表于 2019-11-08 19:45:45">2019-11-08</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-09-07T09:44:01.889Z" title="更新于 2023-09-07 17:44:01">2023-09-07</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/myblog/categories/java/">java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="MordenJava03"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="来玩玩java的Stream"><a href="#来玩玩java的Stream" class="headerlink" title="来玩玩java的Stream"></a>来玩玩java的Stream</h1><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public class HighCaloriesNames &#123;</span><br><span class="line"></span><br><span class="line">  public static void main(String[] args) &#123;</span><br><span class="line">    List&lt;String&gt; names = menu.stream()</span><br><span class="line">        .filter(dish -&gt; &#123;</span><br><span class="line">          System.out.println(&quot;filtering &quot; + dish.getName());</span><br><span class="line">          return dish.getCalories() &gt; 300;</span><br><span class="line">        &#125;)</span><br><span class="line">        .map(dish -&gt; &#123;</span><br><span class="line">          System.out.println(&quot;mapping &quot; + dish.getName());</span><br><span class="line">          return dish.getName();</span><br><span class="line">        &#125;)</span><br><span class="line">        .limit(3)</span><br><span class="line">        .collect(toList());</span><br><span class="line">    System.out.println(names);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>对着代码解析:</strong></p>
<p><strong>所有的流方法参数都是函数式接口</strong>.基于这一点,都可以用lambda表达式操作</p>
<ol>
<li><p>menu不用管就是一个自定义集合.通过<code>.stream()</code> 转换成Stream对象.接着就能玩流式操作了.</p>
</li>
<li><p><code>filter</code> 流的操作方法之一.意思就是过滤的.返回一个布尔值true就通过,false就过滤掉</p>
</li>
<li><p><code>map</code> 流的操作方法之一.map就是收集的意思.返回什么内容,集合里就是什么内容.<code>dish.getName()</code>这里收集的食物的名字</p>
</li>
<li><p><code>limit</code> 流的操作方法之一.意思就是<strong>限制集合元素的数量</strong>.在这里限制集合元素的数量为3</p>
</li>
<li><p><code>collect</code> 流的操作方法之一.意思就是把Stream对象又转换成集合.有几个重载版本.这里我们需要传递一个<code>Collector</code></p>
</li>
<li><p><code>toList</code> 这也是流家族中的.它返回一个Collector对象.也就是和<code>collect</code>配合使用从而把Stream转换成List对象</p>
</li>
</ol>
<p><strong>注意:Stream只能被消费一次</strong>例如:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">List&lt;String&gt; names = Arrays.asList(&quot;Java8&quot;, &quot;Lambdas&quot;, &quot;In&quot;, &quot;Action&quot;);</span><br><span class="line">   Stream&lt;String&gt; s = names.stream();</span><br><span class="line">   s.forEach(System.out::println);</span><br><span class="line">  // s.forEach(System.out::println); //执行这行会报错.</span><br></pre></td></tr></table></figure>
<p>也就是说Stream的消费就是迭代循环出元素之后.将不再能使用了.</p>
<h1 id="构建Stream对象"><a href="#构建Stream对象" class="headerlink" title="构建Stream对象"></a>构建Stream对象</h1><ol>
<li><p><code> Stream.of</code> 创建一个指定元素的Stream对象</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Stream&lt;String&gt; stream = Stream.of(&quot;java8&quot;,&quot;lambdas&quot;,&quot;in&quot;,&quot;Action&quot;);</span><br><span class="line">stream.map(String::toUpperCase).forEach(System.out::println);</span><br></pre></td></tr></table></figure>
<p>output:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">JAVA8</span><br><span class="line">LAMBDAS</span><br><span class="line">IN</span><br><span class="line">ACTION</span><br></pre></td></tr></table></figure></li>
<li><p><code>Stream.empty</code> 创建一个空Stream对象</p>
</li>
<li><p><code>Arrays.stream</code> 数组工具类可以使用这方法把数组转Stream.</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">int[] numbers = &#123;2, 3, 5,&#125;;</span><br><span class="line">System.out.println(Arrays.stream(numbers).sum());</span><br></pre></td></tr></table></figure>
<p>output:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">10</span><br></pre></td></tr></table></figure></li>
<li><p><code>Stream.iterate</code> 使用Stream的迭代器方法生成Stream对象</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"> Stream.iterate(0,n -&gt; n+2)</span><br><span class="line">                .limit(5)</span><br><span class="line">                .forEach(System.out::println);</span><br><span class="line">                System.out.println(&quot;分割--------------------&quot;);</span><br><span class="line">//斐波那契数</span><br><span class="line">Stream.iterate(new int[] &#123; 0, 1 &#125;, t -&gt; new int[] &#123; t[1], t[0] + t[1] &#125;)</span><br><span class="line">                .limit(5)</span><br><span class="line">                .forEach(t -&gt; System.out.printf(&quot;(%d, %d)&quot;, t[0], t[1]));</span><br></pre></td></tr></table></figure>
<p>output:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">0</span><br><span class="line">2</span><br><span class="line">4</span><br><span class="line">6</span><br><span class="line">8</span><br><span class="line">分割-----------------</span><br><span class="line">(0, 1)(1, 1)(1, 2)(2, 3)(3, 5)</span><br></pre></td></tr></table></figure>
<p>第一个参数代表一个初始值,换句话说就是第一个元素.后面的元素按照第二个参数的规则生成</p>
</li>
<li><p><code>Stream.generate</code> 通过提供的表达式生成无序无穷的元素序列.</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Stream.generate(Math::random)</span><br><span class="line">              .limit(3)</span><br><span class="line">              .forEach(System.out::println);</span><br></pre></td></tr></table></figure>
<p>这是根据括号内的lambda表达式生成对应元素,元素的类型和值取决于表达式.</p>
</li>
<li><p><code>IntStream.generate</code> 这个和上一个差不多,区别就是这是专门生成int类型元素的Stream对象</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">IntStream.generate(() -&gt; 1)</span><br><span class="line">                .limit(2)</span><br><span class="line">                .forEach(System.out::println);</span><br></pre></td></tr></table></figure>
<p>output:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">1</span><br><span class="line">1</span><br></pre></td></tr></table></figure></li>
<li><p><code>Files.lines</code> 从一个文件中读取所有的行作为一个Stream,但不像<code>readAllLines(Path, Charset)</code>,这个方法不是把所有的行一次读到一个List中,而是随着流的使用,它才懒加载填充到List中.</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">long uniqueWords = Files.lines(Paths.get(&quot;src\\main\\resources\\com\\pancm\\mordenJava&quot;,&quot;zb\\chap05\\data.txt&quot;), Charset.defaultCharset())</span><br><span class="line">           .flatMap(line -&gt; Arrays.stream(line.split(&quot; &quot;)))</span><br><span class="line">           .distinct()</span><br><span class="line">           .count();</span><br></pre></td></tr></table></figure>
<p>这个例子就是用默认编码去读指定文件,然后用限定符空格分割line产生一个数组,再转成Stream,然后用这个Stream替换原先的<br>Stream,接着去重,计算元素个数.<br><code>flatMap</code> 这个方法就是将产生的新Stream对象替换原先调用flatMap方法的Stream</p>
</li>
</ol>
<p>**注意:**这里的Paths.get方法的路径是文件路径,并不是编译后classes里的文件.可以有多个String参数,如果多个就是后面的追加到前面的String结尾处,最终形成一个完整的路径.</p>
<h1 id="查找Stream里面的元素"><a href="#查找Stream里面的元素" class="headerlink" title="查找Stream里面的元素"></a>查找Stream里面的元素</h1><p>这有点像之前学的正则. 先看代码:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">public class Finding &#123;</span><br><span class="line"></span><br><span class="line">  public static void main(String... args) &#123;</span><br><span class="line">    if (isVegetarianFriendlyMenu()) &#123;</span><br><span class="line">      System.out.println(&quot;Vegetarian friendly&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    System.out.println(isHealthyMenu());</span><br><span class="line">    System.out.println(isHealthyMenu2());</span><br><span class="line"></span><br><span class="line">    Optional&lt;Dish&gt; dish = findVegetarianDish();</span><br><span class="line">    dish.ifPresent(d -&gt; System.out.println(d.getName()));</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  private static boolean isVegetarianFriendlyMenu() &#123;</span><br><span class="line">    return menu.stream().anyMatch(Dish::isVegetarian);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  private static boolean isHealthyMenu() &#123;</span><br><span class="line">    return menu.stream().allMatch(d -&gt; d.getCalories() &lt; 1000);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  private static boolean isHealthyMenu2() &#123;</span><br><span class="line">    return menu.stream().noneMatch(d -&gt; d.getCalories() &gt;= 1000);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  private static Optional&lt;Dish&gt; findVegetarianDish() &#123;</span><br><span class="line">    return menu.stream().filter(Dish::isVegetarian).findAny();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li><p><code>anyMatch</code> 这个方法就是Stream里的元素只要有匹配方法参数里的规则的就返回true.哪怕就一个元素匹配</p>
</li>
<li><p><code>allMatch</code> 这个方法就是<strong>必须一定要</strong>所有的元素都匹配,才返回true否则false</p>
</li>
<li><p><code>noneMatch</code> 这个方法就是<strong>必须一定要</strong>所有的元素都不匹配,才返回true</p>
</li>
<li><p><code>findAny</code> 这个方法返回一个对象容器Optional,这个对象需要满足前面定义的各种过滤,然后最先找到那个满足条件的元素就返回这个元素的对象容器,后面同样满足条件的元素并不会返回..</p>
</li>
</ol>
<h1 id="玩玩数字流"><a href="#玩玩数字流" class="headerlink" title="玩玩数字流"></a>玩玩数字流</h1><p>先来个打印出满足勾股定理的三个整数边长.代码如下:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Stream&lt;int[]&gt; pythagoreanTriples2 = IntStream.rangeClosed(1, 100).boxed()</span><br><span class="line">        .flatMap(a -&gt; IntStream.rangeClosed(a, 100)</span><br><span class="line">        .mapToObj(b -&gt; new double[]&#123;a, b, Math.sqrt(a * a + b * b)&#125;)</span><br><span class="line">        .filter(t -&gt; t[2] % 1 == 0))</span><br><span class="line">        .map(array -&gt; Arrays.stream(array).mapToInt(a -&gt; (int) a).toArray());</span><br><span class="line">    pythagoreanTriples2.forEach(t -&gt; System.out.println(t[0] + &quot;, &quot; + t[1] + &quot;, &quot; + t[2]));</span><br></pre></td></tr></table></figure>
<p><strong>代码解析:</strong></p>
<ol>
<li><p><code>rangeClosed(1,100)</code> 这意思就是包含1到100的有序序列,步长为1.</p>
</li>
<li><p><code>boxed()</code> 意思就是为流中每个int元素打包.返回一个<code>Stream&lt;int&gt;</code>指定为int类型的Stream.</p>
</li>
<li><p><code>mapToObj</code> 意思是收集成对象流.就是流中的元素是对象.</p>
</li>
<li><p><code>mapToInt</code> 这就是收集成int流.</p>
</li>
</ol>
<p>其他: <code>对1取余为0的操作</code> 是为了去除小数的情况,也就是开平方出来的数必须是整数</p>
<h1 id="聚合操作"><a href="#聚合操作" class="headerlink" title="聚合操作"></a>聚合操作</h1><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">List&lt;Integer&gt; numbers = Arrays.asList(3, 4, 5, 1, 2);</span><br><span class="line">  int sum = numbers.stream().reduce(0, (a, b) -&gt; a + b);</span><br><span class="line">   System.out.println(sum);</span><br></pre></td></tr></table></figure>

<p>输出结果:15</p>
<p><strong>代码解析:</strong></p>
<ol>
<li><code>reduce</code> Stream流方法之一.第一个参数的类型就代表返回的类型,并且会被当做第二个参数的迭代的第一个元素a传递进去,第二个参数就是个函数式接口,传方法用的.然后根据传递的表达式规则,把Stream中的元素聚合在一起,并且以第一个参数的类型返回聚合后的数据.</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog">brad 随风起舞</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog/posts/11006/">https://zhangbo4881820.gitee.io/myblog/posts/11006/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhangbo4881820.gitee.io/myblog" target="_blank">静待花开</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/myblog/tags/java/">java</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/myblog/posts/16316/" title="html-study-01"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">html-study-01</div></div></a></div><div class="next-post pull-right"><a href="/myblog/posts/59967/" title="MordenJava02"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MordenJava02</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/myblog/posts/1/" title="Mybatis常用Mapper语句"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-10</div><div class="title">Mybatis常用Mapper语句</div></div></a></div><div><a href="/myblog/posts/1106/" title="数据结构"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-10</div><div class="title">数据结构</div></div></a></div><div><a href="/myblog/posts/60287/" title="MordenJava01"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-08</div><div class="title">MordenJava01</div></div></a></div><div><a href="/myblog/posts/59967/" title="MordenJava02"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-08</div><div class="title">MordenJava02</div></div></a></div><div><a href="/myblog/posts/9473/" title="effective-java(创建和销毁对象--组合的形式优于继承)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-09-11</div><div class="title">effective-java(创建和销毁对象--组合的形式优于继承)</div></div></a></div><div><a href="/myblog/posts/30302/" title="effective-java-(接口优于抽象类)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-09-12</div><div class="title">effective-java-(接口优于抽象类)</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/myblog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">brad 随风起舞</div><div class="author-info__description">有些事情需要一辈子的沉淀</div></div><div class="card-info-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/xxxxx" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:xxxxxx@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%9D%A5%E7%8E%A9%E7%8E%A9java%E7%9A%84Stream"><span class="toc-number">1.</span> <span class="toc-text">来玩玩java的Stream</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%9E%84%E5%BB%BAStream%E5%AF%B9%E8%B1%A1"><span class="toc-number">2.</span> <span class="toc-text">构建Stream对象</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%9F%A5%E6%89%BEStream%E9%87%8C%E9%9D%A2%E7%9A%84%E5%85%83%E7%B4%A0"><span class="toc-number">3.</span> <span class="toc-text">查找Stream里面的元素</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%8E%A9%E7%8E%A9%E6%95%B0%E5%AD%97%E6%B5%81"><span class="toc-number">4.</span> <span class="toc-text">玩玩数字流</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%81%9A%E5%90%88%E6%93%8D%E4%BD%9C"><span class="toc-number">5.</span> <span class="toc-text">聚合操作</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/15695/" title="jenkins（1）">jenkins（1）</a><time datetime="2023-09-14T02:17:44.000Z" title="发表于 2023-09-14 10:17:44">2023-09-14</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/22012/" title="wsl的Ubuntu子系统（1）">wsl的Ubuntu子系统（1）</a><time datetime="2023-09-13T08:42:19.000Z" title="发表于 2023-09-13 16:42:19">2023-09-13</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/30302/" title="effective-java-(接口优于抽象类)">effective-java-(接口优于抽象类)</a><time datetime="2023-09-12T08:12:48.000Z" title="发表于 2023-09-12 16:12:48">2023-09-12</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/9473/" title="effective-java(创建和销毁对象--组合的形式优于继承)">effective-java(创建和销毁对象--组合的形式优于继承)</a><time datetime="2023-09-11T08:23:19.000Z" title="发表于 2023-09-11 16:23:19">2023-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/16107/" title="Hello World">Hello World</a><time datetime="2023-09-07T09:44:01.910Z" title="发表于 2023-09-07 17:44:01">2023-09-07</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By brad 随风起舞</div><div class="framework-info"><span>框架 </span><a href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/myblog/js/utils.js"></script><script src="/myblog/js/main.js"></script><script src="/myblog/js/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/myblog/js/search/local-search.js"></script></div></div></body></html>